package com.zhonghan.recharge.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.zhonghan.common.bean.Result;
import com.zhonghan.common.utils.JiSuOrder;
import com.zhonghan.common.utils.RechargeOrderId;
import com.zhonghan.common.utils.TimerDifferent;
import com.zhonghan.recharge.dao.GascardInfoDao;
import com.zhonghan.recharge.dao.ZhFillCardDao;
import com.zhonghan.recharge.dao.ZhGascardOrderDao;
import com.zhonghan.recharge.pojo.GascardInfo;
import com.zhonghan.recharge.pojo.ZhFillCard;
import com.zhonghan.recharge.pojo.ZhGascardOrder;
import com.zhonghan.recharge.service.JiSuRechargeService;
import com.zhonghan.recharge.service.impl.jisu.JiSuRecharge;
import com.zhonghan.recharge.service.impl.jisu.SmsSendUtils;
import com.zhonghan.recharge.task.TaskList;

@Service
public class JiSuRechargeServiceImpl implements JiSuRechargeService{
	
	private static final Logger logger = LogManager.getLogger(JiSuRechargeServiceImpl.class);
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 油卡充值服务
	 * @param gasnumber  油卡卡号
	 * @param gasname   持卡人
	 * @param gasphone  持卡人电话
	 * @param gastype   油卡类型
	 * @param recardno  序列号
	 * @param password  序列号密码
	 * @param openid
	 * @return
	 */
	@Autowired
    private ZhFillCardDao zhFillCardDao;
	@Autowired
    private ZhGascardOrderDao zhGascardOrderDao;
	
	@Autowired
	private JmsTemplate jmsQueueTemplate;
	
	@Value("test_fill_cards")
	private String test_fill_cards;
	private Object obj= new Object();
	@Transactional
	public Result insertOilRechargeService(String gasnumber, String gasname, String gasphone, String gastype, String recardno,
			String password,String openid) {
		Result result = new Result();
		// 判断
		
		synchronized (obj) {
			ZhFillCard zfc = new ZhFillCard();
			zfc.setSequence(recardno);
			zfc.setPassword(password);
			List<ZhFillCard> zfcList = zhFillCardDao.selectZhFillCardByObj(zfc);
			logger.info("查询到充值卡："+recardno+",个数："+zfcList.size());
			if(zfcList!=null && zfcList.size()>0) {
				zfc = zfcList.get(0);
			}
			
			if(zfc.getStatus()==0 || zfc.getStatus() == 1){
				
				int recard_uses = zhGascardOrderDao.selectOrderIsHavBySequence(recardno);
				logger.info("查询改充值卡是否有订单："+recard_uses);
				if(recard_uses == 0) {
					// 查询到充值卡信息,保存订单
					ZhGascardOrder zgo = new ZhGascardOrder();
					String orderId = RechargeOrderId.getOrderIdJiSu(recardno,zfc.getStatus());
					zgo.setOrderNo(orderId);
				
					zgo.setBmItemId("jisu");
					zgo.setRechargeAmount(zfc.getFacePrice());
					zgo.setBmItemName(zfc.getFacePrice()+"元 - 加油充值卡");
					zgo.setBmItemNum(1);
					zgo.setOpenid(openid);
					zgo.setGascardNo(gasnumber);
					zgo.setTelephone(gasphone);
					zgo.setRechargeState("0");  // 充值状态 0 充值中，1 成功
					zgo.setSalePrice(zfc.getFacePrice());   
					zgo.setOrderType("jisu");   //调用极速订单
					zgo.setFillCardSequence(zfc.getSequence());
					zgo.setFacePrice(zfc.getFacePrice());
					zgo.setOrderTime(sdf.format(new Date()));
						
					zgo.setFillName(gasname);
					zgo.setOperateTime("");
					int rs = zhGascardOrderDao.insertNonEmptyZhGascardOrder(zgo);
					logger.info("生成本地订单："+rs);
					if(rs >0){
						// 订单创建成功并更改中翰云油充值卡状态为已消费
						zfc.setStatus(2);
						zfc.setConsumeTime(sdf.format(new Date()));
						zfc.setReceiveTelephone(gasphone);
						int zfcs = zhFillCardDao.updateNonEmptyZhFillCardById(zfc);
						logger.info("订单创建成功，更改充值的状态为已消费："+zfcs);
						
						//查询调用接口信息
						int num1 = updateGasNumberUse(gasnumber);
						
						
						logger.info("准备调用极速接口");
						/**
						 * 创建参数
						 * orderId ,gasnumber,gasname ,gasphone,facePrice,recardno 
						 */
						final StringBuilder builder = new StringBuilder();
						builder.append(orderId).append(";")
							.append(gasnumber).append(";")
							.append(gasname).append(";")
							.append(gasphone).append(";")
							.append(zfc.getFacePrice()).append(";")
							.append(recardno);
						
						/*jmsQueueTemplate.send("rechargeStr",new MessageCreator() {
							
							@Override
							public Message createMessage(Session session) throws JMSException {
								// TODO Auto-generated method stub
								
								TextMessage message = session.createTextMessage(builder.toString());
								return message;
							}
						});*/
						
						// 推送订单消息给关注的用户
						Map<String,String> textMsgMap = new HashMap<String,String>();
						textMsgMap.put("OpenId", openid);
						textMsgMap.put("OrderNo", orderId);
						final String textMsg = JSON.toJSONString(textMsgMap);
						
						jmsQueueTemplate.send("orderPush",new MessageCreator() {
							
							
							@Override
							public Message createMessage(Session session) throws JMSException {
								
								TextMessage message = session.createTextMessage(textMsg);
								
								return message;
							}
						});
						logger.info("订单消息推送中!");
						result.setCode("1");
						result.setMsg("成功生成充油订单");
						result.setData(orderId);
					}else {
						//订单没有创建成功
						// 没有找到斑马商品
						result.setCode("0");
						result.setMsg("订单创建失败");
						
					}
				}else {
					//订单没有创建成功
					// 没有找到斑马商品
					result.setCode("0");
					result.setMsg("已经有该充值卡订单");
					
				}
				
				
			}else if(zfc.getStatus()==2){
				// 卡已消费
				result.setCode("0");
				result.setMsg("对不起,您输入的卡号已经被消费");
				logger.info("充值卡已消费.....");
				return result;
			}else if(zfc.getStatus()==-1){
				// 卡已消费
				result.setCode("0");
				result.setMsg("对不起,您输入的卡号未激活");
				logger.info("充值卡未激活.....");
				return result;
			}else if(zfc.getStatus()==3){
				//活动取消
				result.setCode("0");
				result.setMsg("对不起,卡片活动期已过,不能消费");
				logger.info("活动期已过,不能消费.....");
				return result;
			}else{
				// 没有查询到油卡信息
				result.setCode("0");
				result.setMsg("充值卡序列号或密码不正确,请检查好后重新输入");
			}
		}
		
		
				
		return result;
	}
	
	
	
	/**
	 * 调用极速订单号
	 * @param orderno  极速订单号 类似斑马订单号
	 * @param outorderno  我们充值系统订单号
	 */
	public Result changeMyOrderRechargeStatusII(String orderno,String outorderno,String appkey) {
		/**
		 * 先去极速查询，
		 * 然后如果状态被改变，修改系统订单状态  充值状态 0充值中 1充值成功 2充值失败 即时返回0
		 * 
		 */
		Result result = new Result();
		JiSuOrder orderDetail = JiSuRecharge.getJiSuOrderDetailII(orderno, outorderno,appkey);
		if(orderDetail != null) {
			logger.info("当前订单号"+orderDetail.getOutorderno()+" 状态为"+orderDetail.getRechargestatus());
			ZhGascardOrder order = zhGascardOrderDao.selectZhGascardOrderByOrderNoII(outorderno,orderno);
			if(orderDetail.getRechargestatus() ==1) {
				//订单成功
				zhGascardOrderDao.updateRechargeStateByOrderNoAndBmBillId(outorderno, "1",sdf.format(new Date()),orderno);
				//电话
				if(order.getTelephone() != null && order.getTelephone().length() == 11) {
					String content = "中翰云：您的充值卡"+order.getFillCardSequence()+",全国"+order.getBmItemName()+",充值成功，谢谢使用。【zhkjnet】";
					SmsSendUtils.send(order.getTelephone(), content);
				}
				
				result.setCode("1");
				result.setData(orderno);
				
				
			}else if(orderDetail.getRechargestatus() ==2) {
				//订单失败
				zhGascardOrderDao.updateRechargeStateByOrderNoAndBmBillId(outorderno, "9",sdf.format(new Date()),orderno);
				
				zhFillCardDao.updateStatusBySequence("1", order.getFillCardSequence());
				result.setCode("2");
			}
		}
		return result;
		
	}
	@Autowired
	private GascardInfoDao gascardinfoDao;
	
	public int  updateGasNumberUse(String gasnumber){
		
		GascardInfo obj = new GascardInfo();
		obj.setCardNo(gasnumber);
		// 保存用户油卡信息到数据库
		GascardInfo gi =gascardinfoDao.selectGascardInfoByObj(obj );
		Integer useNum = gi.getUseNum();
		String oldUseTime = gi.getUseTime();
		int days = 2;
		if(oldUseTime != null) {
			try {
				days = TimerDifferent.differentDaysByMillisecond(sdf.parse(oldUseTime), new Date());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//判断该油卡最近使用时间是否 是当天
		if(days >=1) {
			gi.setUseNum(1);
		}
		if(days <1 && useNum < 5 ) {
			gi.setUseNum(gi.getUseNum() + 1);
		}
		gi.setUseTime(sdf.format(new Date()));
		int num = gascardinfoDao.updateNonEmptyGascardInfoById(gi);
		return num;
	}
	
	/**
	 * 极速调用
	 * 不用充值卡
	 */
	public Result OilRechargeServiceJiSu(String gasnumber, String gasname, String gasphone, String gastype,Integer money){
		Result result = new Result();
			
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ZhGascardOrder zgo = new ZhGascardOrder();
		
		String orderId = RechargeOrderId.getOrderIdBigCustomer();
		zgo.setOrderNo(orderId);
		zgo.setBmItemId("");
		zgo.setRechargeAmount(1);
		zgo.setBmItemName("加油卡直充"+money+"元");
		zgo.setBmItemNum(1);
		zgo.setOpenid("bigCustomer");
		zgo.setGascardNo(gasnumber);
		zgo.setTelephone(gasphone);
		zgo.setFillName(gasname);
		zgo.setRechargeState("0");  // 充值状态 0 充值中，1 成功
		zgo.setSalePrice(money);   
		zgo.setOrderType("jisu");   //调用斑马订单
		zgo.setFacePrice(money);
		zgo.setOrderTime(sdf.format(new Date()));
		//记录大客户
		zgo.setFillCardSequence("bigCustomer");
		zgo.setOperateTime("");
		int rs = zhGascardOrderDao.insertNonEmptyZhGascardOrder(zgo);
		logger.info("生成本地订单："+rs);
				
		//Result oil_result = JiSuRecharge.toRecharge(orderId, gasnumber, gasname, gasphone, money);
		Result oil_result = new Result();
		oil_result.setCode("0");
		if(oil_result != null && "1".equals(oil_result.getCode())) {
			
			result.setCode("1");
			result.setMsg("油卡充值成功!");
			//更改订单状态
			JiSuOrder data = (JiSuOrder)oil_result.getData();
			zhGascardOrderDao.updateRechargeStateByOrderNo(orderId, "0",data.getOrderno());
			logger.info("订单"+orderId+"生成成功");
			result.setData(zgo.getOrderNo());
			//
			TaskList.JISUTASK.put(data.getOrderno(), orderId);
			
			return result;
		}else {
			logger.info("获取极速订单失败..................");
			logger.info("油卡充值失败..............");
			
			zhGascardOrderDao.updateRechargeStateByOrderNo(orderId, "9","faild");
			result.setCode("0");
			result.setMsg("油卡充值失败,请稍后再试");
			
			//throw new RuntimeException(JSON.toJSONString(oil_result));
		}
				
		return result;
	}
	
	public Result oilRechargeServiceJiSuUseOrderId(String gasnumber, String gasname, String gasphone, String orderId,Integer money,String appkey,String appSecret){
		Result result = new Result();
			
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ZhGascardOrder zgo = new ZhGascardOrder();
		
		zgo.setOrderNo(orderId);
		zgo.setBmItemId("");
		zgo.setRechargeAmount(1);
		zgo.setBmItemName("加油卡直充"+money+"元");
		zgo.setBmItemNum(1);
		zgo.setOpenid("bigCustomer");
		zgo.setGascardNo(gasnumber);
		zgo.setTelephone(gasphone);
		zgo.setFillName(gasname);
		zgo.setRechargeState("0");  // 充值状态 0 充值中，1 成功
		zgo.setSalePrice(money);   
		zgo.setOrderType("jisu");   //调用斑马订单
		zgo.setFacePrice(money);
		zgo.setOrderTime(sdf.format(new Date()));
		//记录大客户
		zgo.setFillCardSequence("bigCustomer");
		zgo.setOperateTime("");
		int rs = zhGascardOrderDao.insertNonEmptyZhGascardOrder(zgo);
		logger.info("生成本地订单："+rs);
		
		
				
		Result oil_result = JiSuRecharge.toRechargeII(orderId, gasnumber, gasname, gasphone, money,appkey,appSecret);
		if(oil_result != null && "1".equals(oil_result.getCode())) {
			
			result.setCode("1");
			result.setMsg("油卡充值成功!");
			//更改订单状态
			JiSuOrder data = (JiSuOrder)oil_result.getData();
			zhGascardOrderDao.updateRechargeStateByOrderNo(orderId, "0",data.getOrderno());
			logger.info("订单"+orderId+"生成成功");
			result.setData(zgo.getOrderNo());
			//
			TaskList.JISUTASK.put(data.getOrderno(), orderId+";"+appkey);
			
			return result;
		}else {
			logger.info("获取极速订单失败..................");
			logger.info("油卡充值失败..............");
			
			zhGascardOrderDao.updateRechargeStateByOrderNo(orderId, "9","faild");
			result.setCode("0");
			result.setMsg("油卡充值失败,请稍后再试");
			
			//throw new RuntimeException(JSON.toJSONString(oil_result));
		}
				
		return result;
	}



}
